import Vue from 'vue'
import { login, logout, phoneLogin, thirdLogin, getUserInfo } from '@/api/login'
import {
  ACCESS_TOKEN,
  CACHE_INCLUDED_ROUTES,
  SYS_BUTTON_AUTH_ERP,
  TENANT_ID,
  UI_CACHE_DB_DICT_DATA_ERP,
  USER_AUTH,
  USER_INFO,
  USER_NAME
} from '@/store/mutation-types'
import { welcome, getUrlSearch } from '@/utils/util'
import { queryPermissionsByUser,checkCanFillIn,getUserTypeByUserId } from '@/api/api'
import { getAction } from '@/api/manage'

const user = {
  state: {
    token: '',
    realname: '',
    username: '',
    tenantid: '',
    welcome: '',
    avatar: '',
    permissionList: [],
    info: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { username, realname, welcome }) => {
      state.username = username
      state.realname = realname
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_PERMISSIONLIST: (state, permissionList) => {
      state.permissionList = permissionList
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_TENANT: (state, id) => {
      state.tenantid = id
    }
  },

  actions: {
    // CAS验证登录
    ValidateLogin({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        getAction('/api/erpmng/sys/cas/client/validateLogin', userInfo).then(response => {
          console.log('----cas 登录--------', response);
          if (response.success) {
            const result = response.result
            const userInfo = result.userInfo
            Vue.ls.set(ACCESS_TOKEN, `Bearer ${result.token}`, 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
            commit('SET_TOKEN', `Bearer ${result.token}`)
            commit('SET_INFO', userInfo)
            commit('SET_NAME', { username: userInfo.username, realname: userInfo.realname, welcome: welcome() })
            commit('SET_AVATAR', userInfo.avatar)
            resolve(response)
          } else {
            resolve(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(response => {
          if (response.code == '200') {
            const result = response.result
            const userInfo = result.userInfo
            Vue.ls.set(ACCESS_TOKEN, `Bearer ${result.accessToken}`, 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set('user_id', result.userInfo.id)
            // Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
            // Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
            commit('SET_TOKEN', `Bearer ${result.accessToken}`)
            // commit('SET_INFO', userInfo)
            // commit('SET_NAME', { username: userInfo.username,realname: userInfo.realname, welcome: welcome() })
            // commit('SET_AVATAR', userInfo.avatar)
            // resolve(response)
            getUserInfo({
              username: userInfo.username
            }).then(res => {
              const info = res.result.userInfo
              Vue.ls.set(USER_NAME, info.username, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_INFO, info, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(UI_CACHE_DB_DICT_DATA_ERP, result.sysAllDictItems, 7 * 24 * 60 * 60 * 1000)
              commit('SET_INFO', info)
              commit('SET_NAME', { username: info.username, realname: info.realname, welcome: welcome() })
              commit('SET_AVATAR', info.avatar)
              resolve(res)
            }).catch(err => {
              reject(err)
            })
          } else {
            reject(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 手机号登录
    PhoneLogin({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        console.log('----123')
          phoneLogin(userInfo).then(response => {
          if (response.code == '200') {
        const result = response.result
        const userInfo = result.userInfo
        Vue.ls.set(ACCESS_TOKEN, `Bearer ${result.token}`, 7 * 24 * 60 * 60 * 1000)
        Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
        Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
        Vue.ls.set(UI_CACHE_DB_DICT_DATA_ERP, result.sysAllDictItems, 7 * 24 * 60 * 60 * 1000)
        commit('SET_TOKEN', result.token)
        commit('SET_INFO', userInfo)
        commit('SET_NAME', { username: userInfo.username, realname: userInfo.realname, welcome: welcome() })
        commit('SET_AVATAR', userInfo.avatar)
        resolve(response)
      } else {
        reject(response)
      }
    }).catch(error => {
        reject(error)
      })
    })
    },
    // 获取用户信息
    GetPermissionList({ commit }) {
      return new Promise((resolve, reject) => {
        queryPermissionsByUser().then(response => {
          const menuData = response.result.menu;
          const authData = response.result.auth;
          const allAuthData = response.result.allAuth;
          // Vue.ls.set(USER_AUTH,authData);
          sessionStorage.setItem(USER_AUTH, JSON.stringify(authData));
          sessionStorage.setItem(SYS_BUTTON_AUTH_ERP, JSON.stringify(allAuthData));
          if (menuData && menuData.length > 0) {
            // update--begin--autor:qinfeng-----date:20200109------for：JEECG-63 一级菜单的子菜单全部是隐藏路由，则一级菜单不显示------
            // 递归调用方法 - 处理菜单数据显示位置
            const menuHandle = function(menuData) {
                menuData.forEach((item, index) => {
                  if (item['children']) {
                    // 返回子级菜单不是隐藏路由列表
                    const hasChildrenMenu = item['children'].filter(i => {
                      return !i.hidden || i.hidden === false
                    })
                    // 如果子级菜单全部是隐藏路由
                    if (hasChildrenMenu == null || hasChildrenMenu.length === 0) {
                      item['children'].forEach(childrenItem => {
                        // 隐藏路由无法定位，将父级的path赋值
                        childrenItem.selectedKeys = [item.path]

                        // 子级路由增加字段"isAlwaysShow"
                        childrenItem.meta.isAlwaysShow = item.alwaysShow
                        menuData.push(childrenItem)
                      })
                      item['children'] = null
                    } else {
                      // 如果子级菜单中有不是隐藏的路由
                      // 判断当前菜单是否是否为聚合路由，如果是给所有子级增加字段：'isAlwaysShow'
                      if (item.alwaysShow) {
                        item['children'].forEach(childrenItem => {
                          childrenItem.meta.isAlwaysShow = item.alwaysShow
                        })
                      }
                      menuHandle(item['children'])
                    }
                  }
                })
            }
            menuHandle(menuData)
            // console.log(" menu show json ", menuData)
            // update--end--autor:qinfeng-----date:20200109------for：JEECG-63 一级菜单的子菜单全部是隐藏路由，则一级菜单不显示------
            commit('SET_PERMISSIONLIST', menuData)
          } else {
            reject('getPermissionList: permissions must be a non-null array !')
          }
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 从链接中获取token取代登录
    async getTokenFromAuth({ commit }, userInfo) {
        const paramsArr = ['token', 'username', 'userId']
        const token = await getUrlSearch(paramsArr[0])
        const username = await getUrlSearch(paramsArr[1])
        const userId = await getUrlSearch(paramsArr[2])
        if (!token || !username || !userId) {
          // reject(new Error('参数不存在'))
          return
        }
        if (token) {
          // const token = params.get('token')
          Vue.ls.set('user_id', userId)
          Vue.ls.set(ACCESS_TOKEN, `Bearer ${token}`, 7 * 24 * 60 * 60 * 1000)
          commit('SET_TOKEN', `Bearer ${token}`)
          // 统一认证登录后，获取用户信息
          let res = await getUserInfo({ username })
          if (res.success) {
            let info = res.result.userInfo
            Vue.ls.set(USER_NAME, info.username, 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set(USER_INFO, info, 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set(UI_CACHE_DB_DICT_DATA_ERP, res.result.sysAllDictItems, 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set('showPartSelect', res.result) // 首次进来需要选择部门
            commit('SET_INFO', info)
            commit('SET_NAME', { username: info.username, realname: info.realname, welcome: welcome() })
            commit('SET_AVATAR', info.avatar)
          // const paramsToRemove = ['token', 'username', 'userId']
          let url = new URL(window.location.href)

          for (const param of paramsArr) {
            url.searchParams.delete(param)
          }
          window.location.href = url.toString()
          }
        }
      
    },
    // 必须补填工时才可以进入系统
    async checkMustFillHours() { 
      let aa = await getUserTypeByUserId()
      // 不需要补填工时
      if (aa.result.type === 'white') {
        return 
      }
      let res = await checkCanFillIn({thisWeek:'fill_in'})
      if(res.success){
        return res.result
      }

    },

    // 登出
    Logout({ commit, state }) {
      return new Promise((resolve) => {
        console.log('----123')
        let logoutToken = state.token;
        commit('SET_TOKEN', '')
        commit('SET_PERMISSIONLIST', [])
        Vue.ls.remove(ACCESS_TOKEN)
        Vue.ls.remove(USER_INFO)
        Vue.ls.remove(USER_NAME)
        Vue.ls.remove(UI_CACHE_DB_DICT_DATA_ERP)
        Vue.ls.remove(CACHE_INCLUDED_ROUTES)
        // Vue.ls.remove('subSystem')
        // console.log('logoutToken: '+ logoutToken)
        logout(logoutToken).then(() => {
          if (process.env.VUE_APP_SSO == 'true') {
            let sevice = 'http://' + window.location.host + '/'
            let serviceUrl = encodeURIComponent(sevice)
            window.location.href = process.env.VUE_APP_CAS_BASE_URL + '/logout?service=' + serviceUrl
          }
          resolve()
        }).catch(() => {
          resolve()
        })
      })
    },
    // 第三方登录
    ThirdLogin({ commit }, param) {
      console.log('----123')
      return new Promise((resolve, reject) => {
        thirdLogin(param.token, param.thirdType).then(response => {
          if (response.code == '200') {
            const result = response.result
            const userInfo = result.userInfo
            Vue.ls.set(ACCESS_TOKEN, `Bearer ${result.token}`, 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
            commit('SET_TOKEN', `Bearer ${result.token}`)
            commit('SET_INFO', userInfo)
            commit('SET_NAME', { username: userInfo.username, realname: userInfo.realname, welcome: welcome() })
            commit('SET_AVATAR', userInfo.avatar)
            resolve(response)
          } else {
            reject(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    saveTenant({ commit }, id) {
      Vue.ls.set(TENANT_ID, id, 7 * 24 * 60 * 60 * 1000)
      commit('SET_TENANT', id)
    }

  }
}

export default user
